<!--
禁止修改!此文件是产品代码的一部分，后续可能变更或者不再开放。
若有问题，请参考前端相关二开文档。
-->
<template>
  <div class="form-detail">
    <form-nodes-switch
      v-if="nodes.length > 0"
      :nodes="nodes"
      @nodesSwitch="nodesSwitch"
    />
    <workflow-info
      v-if="workflowBaseInfo && workflowBaseInfo.status"
      ref="workflowInfo"
      :workflowBaseInfo="workflowBaseInfo"
      :itemId="formObj.workItemId"
      :user="creater"
      :currentUrgency="currentUrgency"
      @flowTrack="flowTrack"
    />
    <div
      ref="formBody"
      class="form-body"
      :class="{
        hasnodes: nodes.length > 0,
        workflow: workflowInstanceId,
        'workflow-collapse': workflowCollapse,
      }"
      @scroll="formBodyScoll"
    >
      <transition>
        <toptip v-show="comment">
          {{ comment }}
        </toptip>
      </transition>

      <!-- <transition>
        <toptip v-if="error" class="error">
          {{ error }}
        </toptip>
      </transition> -->
      <!-- 紧急程度 -->
      <mobile-form-renderer
        ref="formRenderer"
        class="form"
        :class="{ 'workflow-form': workflowInstanceId }"
        :controls="controls"
        :relevanceDataList="dataModalList"
        :dataItems="dataItems"
        @scrollTop="onScrollTop"
        @scrollLock="onScrollLock"
        @updateLatestSignature="updateLatestSignature"
      >
        <template slot="content">
          <h3-radio-list
            v-model="formUrgency"
            :editable="formObj.urgencyLevelChoose"
            title="紧急程度"
            :options="urgencyOptions"
            :layout="formObj.bizSheet && formObj.bizSheet.layoutType"
          />
        </template>
      </mobile-form-renderer>
    </div>

    <form-actions
      v-show="mobileActions.length > 0 && tab === 0"
      class="form-foot"
      :actions="mobileActions"
      @action="onAction"
    />

    <form-action-modal
      ref="actionModal"
      :formObj="formObj"
      @ok="onOk"
      @closeModal="onCloseModal"
    />

    <div
      v-if="CommentBtn && tab === 0"
      class="comment-btn"
      :class="{
        moreCount: String(CommentBtn.text).length > 1,
        hidden: hiddenCommentBtn,
      }"
      @click="openCommentBox"
    >
      <span class="comment-icon aufontAll h-icon-all-message-fill"></span>
      <span class="comment-count">{{ CommentBtn.text }}</span>
    </div>

    <FormComment
      v-if="showCommentBox"
      :isWechatOrDingTalk="isDingTalk || isWeChat"
      :formObj="formObj"
      @close="closeCommentBox"
    />

    <template v-if="initiateGroupChatModalVisible">
      <initiateGoupChat
        v-model="initiateGroupChatModalVisible"
        :formObj="formObj"
        :$message="$message"
      />
    </template>

    <template v-if="isAddAndCreateVisible">
      <div class="shadow" @click.self="isAddAndCreateVisible = false"></div>
      <div class="add-type">
        <div class="add-type-item" @click="createEmpty(vm)">
          <span class="add-type-icon">
            <i class="icon aufontAll h-icon-all-add-file-o"></i>
          </span>
          <div class="add-type-text">
            <div>空白新建</div>
            <span>重新填写新表单</span>
          </div>
        </div>

        <div class="add-type-item" @click="createByData(vm)">
          <span class="add-type-icon">
            <i class="icon aufontAll h-icon-all-employment-applicati"></i>
          </span>
          <div class="add-type-text">
            <div>复制新建</div>
            <span>保留本次填写的内容</span>
          </div>
        </div>
      </div>
    </template>

    <WorkflowTrack
      :popVisible="workflowTrackVisible"
      :workflowBaseInfo="workflowBaseInfo"
      @cancel="workflowTrackVisible = false"
    />

    <h3-popup-modal
      v-model="currentDeptSetterShow"
      maskClosable
      wrapCls="radio-wrap current-dept-setter-modal"
      @maskClick="onCloseCurrentDeptSetterModal"
    >
      <template slot="header">
        <div class="options-group">
          <div class="options-sub-group">
            <span @click="onCloseCurrentDeptSetterModal">{{
              $t('cloudpivot.form.renderer.cancel')
            }}</span>
          </div>
          <div class="panel-title">
            <span>{{ $t('languages.common.form.currentDeptSetter') }}</span>
            <span class="panel-title-tips">{{
              $t('languages.common.form.currentDeptSetterTips')
            }}</span>
          </div>
          <div class="options-sub-group">
            <span @click="onOkCurrentDeptSetterModal">{{
              $t('cloudpivot.form.renderer.ok')
            }}</span>
          </div>
        </div>
      </template>
      <div v-if="currentDeptSetterShow">
        <h3-radio-group v-model="currentDeptId" layout="vertical">
          <template v-for="dept in currentDeptSetterList">
            <h3-radio :key="dept.id" :value="dept.id" :label="dept.name" />
          </template>
        </h3-radio-group>
      </div>
    </h3-popup-modal>

    <mobile-custom-list-modal
      class="relevance-form-panel"
      :visible="showCustomListModal"
      :schemaCode="customButtomModalCode"
      :viewCode="viewCodeCustom"
      :listSearchFormula="searchFormula"
      :currentFormData="currentFormData"
      :sheetCode="currentSheetCode"
      :currentSchemaCode="currentSchemaCode"
      modalName="查看列表"
      @back="onCustomListModalClose"
      @toFormDetail="toFormDetail"
    />
  </div>
</template>

<script lang="ts">
import env from '@/config/env';
import '@/config/h3-form';
import * as FormCommentIns from 'cloudpivot/api';
import { externalLinkApi, listApi, formApi, listParams } from 'cloudpivot/api';
import common from 'cloudpivot/common/mobile';
import flow from 'cloudpivot-flow/flow/mobile';
import { renderer, runtime, schema } from 'cloudpivot-form/form';
import * as mobileForm from 'cloudpivot-form/form/mobile';
import * as platform from 'cloudpivot-platform/platform';
import { FormSheet } from 'cloudpivot-forms';
import { Component, Provide, Watch } from 'vue-property-decorator';
import formNodesSwitch from './form-nodes-switch.vue';
import * as dd from 'dingtalk-jsapi';
import { DataItemType, FormAction } from 'cloudpivot-form/form/schema';
import { formatVal } from 'cloudpivot-list/list/src/utils/query-form-util';
import FormComment from 'cloudpivot-form/form/src/runtime/components/mobile/formComment/index.vue';
import WorkflowTrack from './workflow-track.vue';
import * as Back from 'cloudpivot/common/src/config/mobile/back';
import { getUrlStroage } from 'cloudpivot/common/src/utils/url';
import FormDetail from 'cloudpivot-form/form/src/runtime/components/form-detail';
import { H3RadioList } from 'cloudpivot-mobile-vue';
import MobileCustomListModal from 'cloudpivot-form/form/src/common/components/mobile-custom-list-modal.vue';

import {
  DynamicDateRangeType,
  ValueTypeWithInput,
  ValueTypesWithoutInput,
} from 'cloudpivot-form/form/src/common/components/condition-group/typings';

import * as Helper from 'cloudpivot-list/list/src/components/pc/helper/helper';
import { H3PopupModal, H3Radio } from '@h3/thinking-ui';
import { namespace } from 'vuex-class';

const UserModule = namespace('System/User');

const DateType = {
  // 本周
  [DynamicDateRangeType.ThisWeek]: 5,
  // 本月
  [DynamicDateRangeType.ThisMonth]: 6,
  // 本季度
  [DynamicDateRangeType.ThisQuarter]: 7,
  // 本年
  [DynamicDateRangeType.ThisYear]: 8,
  // 最近一周
  [DynamicDateRangeType.LastWeek]: 1,
  // 最近一月
  [DynamicDateRangeType.LastMonth]: 2,
  // 最近一季度
  [DynamicDateRangeType.LastQuarter]: 3,
  // 最近一年
  [DynamicDateRangeType.LastYear]: 4,
  // 过去
  [DynamicDateRangeType.Past]: 10,
  // 未来
  [DynamicDateRangeType.Future]: 11,
};

const isFormPcDdMessage = () => {
  return location.href.indexOf('formPcdd') !== -1;
};

/**
 * @Author: Fan
 * @Description: 在钉钉OA工作台 不能打开移动端页面, 需要跳转到PC端
 * @Date: 2020-01-15 00:35:49
 */
function checkRunPlatform(to) {
  if (
    platform.IS_DINGTALK &&
    common.utils.Common.isPC &&
    !isFormPcDdMessage()
  ) {
    const url = `${(window as any).config.portalHost}${
      to.fullPath
    }&T=${localStorage.getItem('token')}`;
    platform.service.openLink(url);
    // window.open(url,'_blank')
    return [false, url];
  }
  return [true, ''];
}

Component.registerHooks([
  'beforeRouteEnter',
  'beforeRouteLeave',
  'beforeRouteUpdate',
]);

@Component({
  name: 'mobile-form-detail',
  components: {
    Toptip: common.components.Toptip,
    WorkflowInfo: flow.components.WorkflowInfo,
    FormActions: mobileForm.runtime.FormActions,
    MobileFormRenderer: mobileForm.renderer.FormRenderer,
    FormActionModal: mobileForm.runtime.FormActionModal,
    initiateGoupChat: mobileForm.runtime.initiateGoupChat,
    formNodesSwitch,
    FormComment,
    WorkflowTrack,
    H3RadioList,
    H3Radio,
    H3RadioGroup: H3Radio.Group,
    H3PopupModal,
    MobileCustomListModal,
  },

  beforeRouteEnter(to, from, next) {
    const [st, url] = checkRunPlatform(to);
    if (st) {
      next((vm) => {
        (vm as MobileFormDetail).beforeLoad();
      });
    } else {
      next({
        path: `/form/empty?openBrowser=${url}`,
        replace: true,
      });
    }
  },

  beforeRouteUpdate(to, from, next) {
    const vm = this as MobileFormDetail;
    // vm.clean();
    next();
    vm.beforeLoad();
  },

  beforeRouteLeave(to, from, next) {
    let user: any = sessionStorage.getItem('user');
    if (user) {
      user = JSON.parse(user);
    }
    localStorage.removeItem(`${user.name}_latestSign`);
    next();
  },
})
export default class MobileFormDetail extends FormDetail {
  @UserModule.Mutation('setUserInfo') setLoginUserInfo: any;

  creater: any = {};

  timer: any = null;

  loadding: boolean = false;

  // todo: 待优化代码，需要监听axios的事件
  percent: number = 0;
  // timers = 0;

  error = '';

  tab: number = 0;

  showCommentBox: boolean = false;

  actionRunning: boolean = false;

  get setUserInfo() {
    return this.setLoginUserInfo;
  }

  @Watch('canSubmit', { immediate: true })
  onIsNewChange(val) {
    console.log(this.canSubmit);
  }

  //移动端流程跟踪需要单独
  workflowTrackVisible: boolean = false;

  @Provide()
  formTabActiveTab(tab: number) {
    this.tab = tab;
    this.controlFormBodyStyle(this.actions);
  }

  @Provide()
  getFormVal() {
    return this.getFormValFn();
  }

  @Provide()
  formObjSource() {
    return this.formObj;
  }

  @Provide()
  getImportFormValue() {
    const importFormValue = this.getFormValue(false, false);
    this.formatData(importFormValue);
    return importFormValue;
  }

  get isMobile() {
    return true;
  }

  get isDingTalk() {
    return platform.IS_DINGTALK;
  }

  get isWeChat() {
    return platform.IS_WECHAT;
  }

  get currentFormData() {
    const formObj = this.formObj;
    return (formObj && formObj.bizObject && formObj.bizObject.data) || {};
  }

  get currentSheetCode() {
    const formObj = this.formObj;
    return (formObj && formObj.bizObject && formObj.bizObject.sheetCode) || '';
  }

  get currentSchemaCode() {
    const formObj = this.formObj;
    return (formObj && formObj.bizObject && formObj.bizObject.schemaCode) || '';
  }

  isAddAndCreateVisible: boolean = false;

  workflowCollapse: boolean = false;

  get vm() {
    return this;
  }

  approvals: any[] = [];

  async mounted() {
    const stroage = sessionStorage.getItem('theQueryList2');
    if (stroage) {
      sessionStorage.setItem('theQueryList3', stroage);
    }
    sessionStorage.removeItem('theQueryList2');
    localStorage.removeItem('isShowEmailResquest');
    this.initCustomListModal();
    this.$nextTick(() => {
      setTimeout(() => {
        const formWrap = this.$refs.formRenderer as any;
        // const formRenderer = formWrap.$refs.formRenderer as any;
        const formRenderer = this.$refs.formRenderer as any;
        if (!formRenderer) {
          return;
        }
        this.$watch(
          () => formRenderer.getErrors(),
          (errors: any) => {
            if (errors) {
              const keys = Object.keys(errors);
              if (keys.length > 0) {
                const key = keys[0];
                // 防止将上一次的错误提示清空 #43219
                if (this.error === '') {
                  this.error = formRenderer.getErrorMessage(
                    key,
                    errors[key][0],
                  );
                }
                return;
              }
            }
            this.error = '';
          },
          {
            immediate: true,
          },
        );
      }, 200);
    });
  }

  // 页面销毁的时候
  destroyed() {
    clearInterval(this.timer);
    sessionStorage.removeItem('openFormDetail');
  }

  get $message() {
    return {
      error: (msg: string) => {
        this.showError(msg);
      },
      success: (msg: string) => {
        this.showSuccess(msg);
      },
      loading: (msg?: string) => {
        this.showLoading(msg || '');
        return this.hideToast;
      },
      info: (msg?: string) => {
        this.showInfo(msg || '');
      },
    } as any;
  }

  get $confirm() {
    return ((opts: {
      title: string;
      content: string;
      okText: string;
      cancelText: string;
      wrapCls: string;
      onOk?: () => void;
      onCancel?: () => void;
    }) => {
      (this as any).$modal.confirm({
        title: opts.title,
        content: opts.content,
        wrapCls: 'form-confirm-modal ' + opts.wrapCls,
        cancelText:
          opts.cancelText ||
          (this as any).$t('cloudpivot.form.renderer.cancel').toString(),
        confitmText:
          opts.okText ||
          (this as any).$t('cloudpivot.form.renderer.ok').toString(),
        onCancel() {
          if (opts.onCancel) {
            opts.onCancel();
          }
        },
        onConfirm() {
          if (opts.onOk) {
            opts.onOk();
          }
        },
      });
    }) as any;
  }

  CommentBtn: any = null;

  get mobileActions() {
    const sorts: any = {
      submit: 1,
      agree: 1,
      disAgree: 2,
      save: 2,
      showReject: 2,
      edit: 2,
      urge: 3,
      copy: 3,
      comment: 4,
      initiateGroupChat: 100,
    };

    const index = this.actions.findIndex((ac) => ac.code === 'comment');
    if (~index) {
      this.CommentBtn = this.actions[index];
    } else {
      this.CommentBtn = null;
    }

    this.actions.sort(
      (a, b) =>
        (sorts[b.code] ? sorts[b.code] : 99) -
        (sorts[a.code] ? sorts[a.code] : 99),
    );

    let mobileActions = this.actions.filter(
      (ac) =>
        ac.visible !== false &&
        ac.code !== runtime.FormAction.Print &&
        ac.code !== runtime.FormAction.EditOwner,
    );

    if (this.isNew) {
      mobileActions.splice(1, 0, {
        // @ts-ignore
        code: 'addAndCreate',
        disabled: false,
        loading: false,
        text: '提交并继续创建',
      });
    }
    mobileActions = mobileActions.filter(
      (item) => item.code !== 'formTrack' && item.code !== 'comment',
    );
    return mobileActions;
  }

  get dataItems() {
    if (this.formObj.bizSchema && this.formObj.bizSchema.properties) {
      return this.formObj.bizSchema.properties;
    }

    return [];
  }

  /**
   * 评论模块需要判断当前表单是否提交过
   */
  get isSsubmited() {
    if (this.isWorkflowForm) {
      return !!this.formObj.workflowInstanceIsSubmit;
    }

    return this.formObj.bizObject.data.sequenceStatus === 'COMPLETED';
  }

  /**
   * 根据表单配置项是否加载评论模块
   */
  get isLoadComment() {
    if (this.formObj.bizSheet) {
      return this.formObj.bizSheet.formComment;
    }

    return false;
  }

  get isMobileTerminal() {
    const flag = navigator.userAgent.match(
      /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i,
    );
    return flag;
  }

  /**
   * 当紧急程度发生改变时
   */
  onUrgencyChange(value: any) {
    this.formUrgency = value;
  }

  /**
   * 流程表单formRenderer上下滑动监听事件
   */
  formRendererTouchMove() {
    const vm = this;
    const formRenderer = (vm.$refs.formRenderer as any).$el;
    const formBody = vm.getFormBody();
    var startY, endY;
    //因钉钉PC端需要触发侧边栏打开进入移动端表单，所以判断是否为移动端，移动端使用touch事件，PC端使用scroll事件
    if (this.isMobileTerminal) {
      formRenderer.addEventListener('touchstart', touchStart, true);
      formRenderer.addEventListener('touchmove', touchMove, true);
    } else {
      let oldScrollTop = 0;
      formBody.addEventListener(
        'scroll',
        function () {
          // 滚动条距文档顶部的距离
          let scrollTop: any =
            window.pageYOffset ||
            document.documentElement.scrollTop ||
            formBody.scrollTop;
          // 滚动条滚动的距离
          let scrollStep = scrollTop - oldScrollTop;
          // 更新——滚动前，滚动条距文档顶部的距离
          oldScrollTop = scrollTop;

          /**
           * console.log('scrollTop',scrollTop)
           * 触顶之后将头部展开
           * 往下滑动之后将头部折叠
           */
          if (scrollStep < 0 && scrollTop === 0) {
            console.log('滚动条向上滚动了！');
            // 展开
            vm.workflowInfoBodyCollapse(false);
          } else if (scrollTop > 30) {
            console.log('滚动条向下滚动了！');
            // 折叠
            vm.workflowInfoBodyCollapse(true);
          }
        },
        true,
      );
    }
    function touchStart(event) {
      var touch = event.touches[0];
      startY = touch.pageY;
    }
    function touchMove(event) {
      var workflowInfo = (vm.$refs.workflowInfo as any).$el;
      var touch = event.touches[0];
      endY = touch.pageY;
      var distanceY = endY - startY;
      //表单滚动条当前处于最顶部的时候滑动才生效
      if (formBody && formBody.scrollTop === 0) {
        const iscollapse = workflowInfo.classList.contains('collapse');
        //当前为展开，往下滚动时，将formBody滚动禁用
        if (!iscollapse) {
          vm.onScrollLock(true);
        }
        if (distanceY > 0) {
          // 展开
          vm.workflowInfoBodyCollapse(false);
        } else {
          // 折叠
          vm.workflowInfoBodyCollapse(true);
        }
        //将formBody滚动启用
        setTimeout(() => {
          vm.onScrollLock(false);
        }, 50);
      }
    }
  }

  /**
   * 流程表单头部控制折叠展开
   */
  workflowInfoBodyCollapse(collapse) {
    const workflowInfo = (this.$refs.workflowInfo as any).$el;
    const formBody = this.getFormBody();
    if (collapse) {
      //流程表单头部折叠
      workflowInfo.classList.add('collapse');
      workflowInfo.style.height = `${48}px`;
      this.workflowCollapse = true;
      let collapseHeight = '';
      if (this.mobileActions.length && this.tab === 0) {
        /**
          有操作按钮
          有节点选择60+36+48
          无操作节点60+48
          */
        collapseHeight = this.nodes.length
          ? 'calc(100% - 144px)'
          : 'calc(100% - 108px)';
        // collapseHeight = this.nodes.length
        //   ? 'calc(100% - 4.05333333rem)'
        //   : 'calc(100% - 108px)';
      } else {
        /**
          无操作按钮
          有节点选择36+48
          无操作节点48
          */
        collapseHeight = this.nodes.length
          ? 'calc(100% - 84px)'
          : 'calc(100% - 48px)';
        // collapseHeight = this.nodes.length
        //   ? 'calc(100% - 92px)'
        //   : 'calc(100% - 48px)';
      }
      formBody.style.height = collapseHeight;
      formBody.style['border-radius'] = '0';
      formBody.style['border-top'] = '1px solid rgba(209,211,228,0.48)';
    } else {
      //流程表单头部展开
      workflowInfo.classList.remove('collapse');
      workflowInfo.style.height = `${225}px`;
      this.workflowCollapse = false;
      let uncollapseHeight = '';
      if (this.mobileActions.length && this.tab === 0) {
        /**
          有操作按钮
          有节点选择60+36+225
          无操作节点60+225
          */
        uncollapseHeight = this.nodes.length
          ? 'calc(100% - 321px)'
          : 'calc(100% - 285px)';
        // uncollapseHeight = this.nodes.length
        //   ? 'calc(100% - 8.77333333rem)'
        //   : 'calc(100% - 285px)';
      } else {
        /**
          无操作按钮
          有节点选择36+225
          无操作节点225
          */
        uncollapseHeight = this.nodes.length
          ? 'calc(100% - 261px)'
          : 'calc(100% - 225px)';
        // uncollapseHeight = this.nodes.length
        //   ? 'calc(100% - 7.17333333rem)'
        //   : 'calc(100% - 225px)';
      }
      formBody.style.height = uncollapseHeight;
      formBody.style['border-radius'] = '20px 20px 0px 0px';
      formBody.style['border-top'] = '1px solid transparent';
    }
  }

  @Provide()
  layoutTypeFn() {
    return (
      this.formObj &&
      this.formObj.bizSheet &&
      this.formObj.bizSheet.layoutType === 'vertical'
    );
  }
  // @Provide()
  // message() {
  //   return this.$message
  // }

  showLoading(text: string) {
    (this as any).$h3.toast.show({
      text,
      autoHide: false,
      iconType: 'loading',
    });
  }

  showError(text: string) {
    (this as any).$h3.toast.show({
      text,
      autoHide: true,
      iconType: text.length < 8 ? 'close' : '',
    });
  }

  showSuccess(text: string) {
    (this as any).$h3.toast.show({
      text,
      autoHide: true,
      iconType: 'check',
      duration: 1000,
    });
  }

  showInfo(text: string) {
    (this as any).$h3.toast.show({
      text,
      autoHide: true,
      iconType: 'info',
      duration: 1000,
    });
  }

  hideToast() {
    (this as any).$h3.toast.hide();
  }

  @Watch('mobileActions')
  onMobileActionsChange(actions: runtime.FormActionButton[]) {
    if (this.$el) {
      this.controlFormBodyStyle(actions);
    }
  }

  /**
   * 控制FormBody初始化以及切换操作节点后样式
   */
  controlFormBodyStyle(action) {
    const formBody = this.getFormBody();
    if (formBody) {
      let height = '';
      if (action.length > 0 && this.tab === 0) {
        // height = this.nodes.length > 0 ? 'calc(100% - 100px)' : 'calc(100% - 60px)';
        if (this.workflowInstanceId) {
          /**
           * 有操作按钮
           * 有操作节点60+36+225
           * 无操作节点60+225
           */
          height = !this.workflowCollapse
            ? this.nodes.length > 0
              ? 'calc(100% - 321px)'
              : 'calc(100% - 285px)'
            : this.nodes.length > 0
            ? 'calc(100% - 144px)'
            : 'calc(100% - 108px)';
          // this.nodes.length > 0 ? 'calc(100% - 321px)' : 'calc(100% - 285px)';
          // height =
          //   this.nodes.length > 0
          //     ? 'calc(100% - 8.77333333rem)'
          //     : 'calc(100% - 285px)';
          formBody.style['border-radius'] = '20px 20px 0px 0px';
        } else {
          // height = 'calc(100% - 60px)';
          height = 'calc(100% - 60px)';
        }
      } else {
        if (this.workflowInstanceId) {
          /**
           * 无操作按钮
           * 有操作节点36+225
           * 无操作节点225
           */
          height = !this.workflowCollapse
            ? this.nodes.length > 0
              ? 'calc(100% - 261px)'
              : 'calc(100% - 225px)'
            : this.nodes.length > 0
            ? 'calc(100% - 84px)'
            : 'calc(100% - 48px)';
          // height =
          //   this.nodes.length > 0
          //     ? 'calc(100% - 7.17333333rem)'
          //     : 'calc(100% - 225px)';
        } else {
          height = '100%';
        }
      }
      formBody.style.height = height;
    }
  }

  getFormBody() {
    return this.$el.querySelector('.form-body') as HTMLDivElement;
  }

  onScrollTop(top: number) {
    const formBody = this.getFormBody();
    if (formBody) {
      formBody.scrollTop = top;
    }
  }

  onScrollLock(lock: boolean) {
    const formBody = this.getFormBody();
    if (formBody) {
      formBody.style['overflow-y'] = lock ? 'hidden' : 'auto';
    }
  }

  validate(onlyUpload?: boolean) {
    const formRenderer = this.$refs.formRenderer as any;
    // formRenderer = formRenderer.$refs.formRenderer as any;

    let valid = false;

    const formControls: renderer.RendererFormControl[] = [];
    renderer.components.FormRendererHelper.findFormControl(
      this.controls,
      formControls,
    );

    if (!onlyUpload) {
      if (this.approval) {
        valid = formRenderer.validate([this.approval.key]);
      } else {
        valid = formRenderer.validate();
      }

      const rowEmpty = (this as any).$t(
        'cloudpivot.form.runtime.modal.rowEmpty',
      );
      const isEmptyRow: boolean = formControls
        .filter(
          (c) =>
            c.type === schema.FormControlType.Sheet && c.options.isEmptyRow,
        )
        .some((c) => {
          const ctrl = this.formRenderer.controller.findChild(
            c.key,
          ) as FormSheet;
          const name =
            (this as any).$i18n.locale === 'zh'
              ? c.options.name
              : c.options.name_i18n
              ? c.options.name_i18n
              : 'Subtable';
          // 如果子表不显示 则不做空行判断
          if (ctrl && !ctrl.display) {
            return false;
          }
          if (ctrl && ctrl.value.length === 0) {
            this.$message.error(`${name}${rowEmpty}`, 3);
            return true;
          } else if (ctrl && ctrl.value.length) {
            const sheetVal = ctrl.value.map((el) => {
              let res = { ...el };
              delete res.rowStatus;
              return res;
            });

            const isValue: boolean = sheetVal.every((s: any) => {
              return Object.values(s).join('').length > 0;
            });
            if (!isValue) {
              this.$message.error(`${name}${rowEmpty}`, 3);
              return true;
            }
          } else {
          }
          return false;
        });

      if (isEmptyRow) {
        return false;
      }

      const pleaseInput = (this as any).$t(
        'cloudpivot.form.runtime.modal.pleaseInput',
      );

      // this.formControls = formControls;
      let isRequire: boolean = formControls
        .filter((c) => c.type === renderer.FormControlType.Address)
        .some((c: any) => {
          const ctrl = this.formRenderer.controller.findChild(c.key);
          // const val: any = c.controller.value;
          if (
            ctrl &&
            ctrl.required &&
            (!ctrl.value || !ctrl.value.provinceAdcode)
          ) {
            this.$message.error(`${pleaseInput}${c.options.name}`);
            return true;
          }

          return false;
        });

      if (!isRequire) {
        isRequire = formControls
          .filter((c) => c.type === schema.FormControlType.Sheet && c.required)
          .some((c) => {
            const ctrl = this.formRenderer.controller.findChild(
              c.key,
            ) as FormSheet;
            if (ctrl && ctrl.rows.length === 0) {
              this.$message.error(`${pleaseInput}${c.options.name}`);
              return true;
            }
            return false;
          });
      }

      if (isRequire) {
        return false;
      }
    }

    const formBody = this.$el.querySelector('.form-body') as HTMLDivElement;

    const scrollTo = (
      key: string,
      isSheet: boolean = false,
      isWaterfallTable: boolean = false,
    ) => {
      let el = this.$el.querySelector(`#${key}`) as HTMLDivElement;
      if (isSheet) {
        const child = this.$el.querySelector(
          `#${key} .error`,
        ) as HTMLDivElement;
        if (child && formBody) {
          if (isWaterfallTable) {
            formBody.scrollTop = child.offsetTop;
          } else {
            formBody.scrollTop = el.offsetTop + child.offsetTop;
          }
        } else {
          if (el && formBody) {
            formBody.scrollTop = el.offsetTop - el.offsetHeight;
          }
        }
      } else {
        if (el && formBody) {
          formBody.scrollTop = el.offsetTop - el.offsetHeight;
        }
      }
    };

    if (!onlyUpload) {
      if (!valid) {
        const errors = formRenderer.getErrors();
        if (errors) {
          let keys = Object.keys(errors);
          if (keys.length > 0) {
            let key = keys[0];
            const control: any = formControls.find((c) => c.key === key);
            let isWaterfallTable: boolean = false;
            if (control && control.type === schema.FormControlType.Sheet) {
              const map = errors[key];
              keys = Object.keys(map);
              const keys2 = Object.keys(map[keys[0]]);
              const err = formRenderer.getErrorMessage(
                keys2[0],
                map[keys[0]][keys2[0]][0],
                key,
              );
              this.error = err;
            } else {
              this.error = formRenderer.getErrorMessage(key, errors[key][0]);
            }

            setTimeout(() => {
              // 校验失败获取赋予输入框焦点
              const input: any = document.querySelector(
                '#' + key + ' input',
              ) as any;
              const textarea: any = document.querySelector(
                '#' + key + ' textarea',
              ) as any;
              input && input.focus();
              textarea && textarea.focus();
            }, 300);
            this.hideError();

            if (control && control.type === schema.FormControlType.Sheet) {
              setTimeout(() => {
                scrollTo(key, true, isWaterfallTable);
              }, 300);
            } else {
              scrollTo(key);
            }
            return false;
          }
        }
      }
    }

    let upload = super.findUploadBy(renderer.UploadStatus.Uploading);
    if (upload) {
      this.error = `${upload.options.name}正在上传！`;
      this.hideError();
      scrollTo(upload.key);
      return false;
    }

    upload = super.findUploadBy(renderer.UploadStatus.Error);
    if (upload) {
      this.error = `${upload.options.name}上传失败！`;
      this.hideError();
      scrollTo(upload.key);
      return false;
    }

    this.error = '';

    return true;
  }

  //顶部弹出提示信息，1200ms后自动消失，避免遮挡第一行的数据项
  hideError() {
    setTimeout(() => {
      this.error = '';
    }, 1200);
  }

  async beforeLoad() {
    this.onScrollLock(false);
    this.workflowTrackVisible = false;
    if (this.isWorkFlowSheet) {
      this.nodes = await (this.getWorkFlowNodes() as any);
      const params: any = this.$route.query;
      const workitemId: any = params.workitemId;
      this.nodes.forEach((res, index) => {
        if (workitemId && res.id === workitemId) {
          res.selected = true;
        } else {
          res.selected = false;
        }
      });
      if (this.nodes.length > 0) {
        const nodeItem = this.nodes.find((item) => item.selected);
        if (nodeItem) {
          this.getNodesParams(nodeItem.activityCode);
        } else {
          this.getNodesParams(this.nodes[0].activityCode);
        }
      }
      this.load();
    } else {
      const staffShowModal = sessionStorage.getItem('staffShowModal');
      if (staffShowModal === 'true') {
        sessionStorage.setItem('staffShowModal', 'false');
      } else {
        this.nodesParams = null;
        this.load();
      }
    }
  }

  nodesSwitch(node: string) {
    this.getNodesParams(node);
    this.clean(true);
    this.load();

    this.controlFormBodyStyle(this.actions);
  }

  get isEL() {
    return !!(window as any).externalLinkToken;
  }

  async load(edit?: boolean) {
    // const closeLoading = (this.$message as any).loading();
    this.loadding = true;
    try {
      const res = await super.load(edit);
      if (res && res.errcode !== 0) {
        throw res;
      }
      const title = this.formObj.instanceName || this.formObj.bizSheet.name;
      if (platform && platform.service && platform.service.setTitle) {
        // 外链和从列表中打开的表单的新建、查看、编辑状态 移动端表单顶部 表单 去掉 #34950 迭代30
        if (this.nodes.length || this.isEL) {
          (window as any).pageTitle = ' ';
          platform.service.setTitle(' ');
        } else {
          (window as any).pageTitle = title;
          platform.service.setTitle(title);
        }
      }
      const creaters = this.formObj.bizObject.data.creater;
      if (creaters && Array.isArray(creaters)) {
        this.creater = creaters[0];
      }

      if (this.approval) {
        setTimeout(() => {
          this.approval.controller = (this.formRenderer as any).findController(
            this.approval.key,
          );
        }, 500);
      }
      if (this.isSsubmited && this.isLoadComment && !this.isEL) {
        this.getCommListNum();
      }
    } catch (e) {
      if (e instanceof Error) {
        // alert(e);
        console.error(e);
      }
      if (e.errcode === 302034) {
        // this.error = "该表单未发布，请联系管理员处理";
        this.goUnpublished();
        return;
      }
      if (
        e.errcode === 601010 ||
        e.errcode === 6000018 ||
        e.errmsg.indexOf('权限') > -1
      ) {
        this.goPermission();
        return;
      }
      this.goEmptyPage();
    } finally {
      // closeLoading();
      this.loadding = false;
    }

    //流程表单头部折叠
    if (this.formObj.workflowInstanceId) {
      this.formRendererTouchMove();
    }
  }

  async onActionModalOk(ac: runtime.FormActionButton, data: any) {
    if (ac.code === runtime.FormAction.Reject && !super.validateApproval()) {
      return;
    }
    return super.onActionModalOk(ac, data);
  }

  initIframe(url: string) {
    const { bizSheet } = this.formObj;
    if (bizSheet && !bizSheet.mobileIsPc) {
      url = bizSheet.mobileUrl;
    }
    const iframe = super.initIframe(url);
    const w = iframe.contentWindow as any;
    w.env = env;
    w.config = env;
    return iframe;
  }

  onOk(ac: runtime.FormActionButton, data: any) {
    //
    super.doAction(ac, data);
  }

  async onAction(ac: runtime.FormActionButton) {
    if (this.actionRunning) {
      return;
    }
    this.actionRunning = true;
    if (ac.custom) {
      this.customButtonFun(ac);
    } else {
      await super.onAction(ac);
    }
    this.actionRunning = false;
  }

  updateLatestSignature(value: any, isNew: boolean = false) {
    super.updateLatestSignature(value, isNew);
  }

  async goto(ac: runtime.FormActionButton, res: Common.Data) {
    //
    // switch(ac.code) {
    //   case runtime.FormAction.Save:
    // }
    // this.onScrollLock(true);
    if (ac.code === runtime.FormAction.Save) {
      //移动端与pc端提示保持一致，提示逻辑都在顶层form-detail文件中的doAction方法中
      // if (this.isNew) {
      //   this.$message.success(
      //     (this as any).$t(
      //       `cloudpivot.form.runtime.actionTip.${ac.code}`,
      //     ) as string,
      //   );
      // } else {
      //   this.$message.success(
      //     (this as any).$t(`cloudpivot.form.runtime.actionTip.save2`) as string,
      //   );
      // }
      setTimeout(() => {
        this.hideToast();

        if (this.isWorkflowForm) {
          const params: any = this.$route.query;
          const workitem = res.data.workItem;
          if (workitem) {
            this.goWfForm(workitem.id, workitem.instanceId);
          } else if (params.workitemId && params.workflowInstanceId) {
            this.goWfForm(params.workitemId, params.workflowInstanceId);
          } else {
            this.goWfForm(params.workitemId, res.data.workflowInstanceId);
          }
        } else {
          this.goBizForm();
        }
      }, 2000);
    } else if (ac.code === runtime.FormAction.Retrieve) {
      // 撤回刷新页面
      const workflowInstanceId = this.$route.query.workflowInstanceId as string;
      const workitemId = this.$route.query.workitemId as string;
      if (res.data.id === workitemId) {
        this.reload();
        this.workflowInstanceId = '';
        this.$nextTick(() => {
          this.workflowInstanceId = workflowInstanceId;
        });
      } else {
        this.goWfForm(res.data.id, workflowInstanceId);
      }

      // this.retrieveCallBack();
    } else {
      // this.$message.success(
      //   (this as any).$t(
      //     `cloudpivot.form.runtime.actionTip.${ac.code}`,
      //   ) as string,
      // );

      setTimeout(() => {
        sessionStorage.removeItem('theQueryList3');
        let url: string =
          getUrlStroage(this.$route.query.return as string) ||
          (this.$route.query.return as string) ||
          (window.sessionStorage.getItem('fullPath') as string);
        if (
          this.$route.name === 'form-detail' &&
          location.pathname !== '/mobile/el.html'
        ) {
          if ((window as any).dd?.closePage) {
            if (url) {
              this.$router
                .push({
                  path: url,
                })
                .catch((err: any) => {
                  console.log(err);
                });
            } else {
              (window as any).dd?.closePage();
            }
          } else if (dd.biz && (dd.android || dd.ios)) {
            if (url) {
              this.$router
                .push({
                  path: url,
                })
                .catch((err: any) => {
                  console.log(err);
                });
            } else {
              if (window.Environment.historyLength === 1) {
                dd.biz.navigation.close({});
                return;
              }
              dd.biz.navigation.goBack({
                onSuccess: () => {
                  console.log('关闭成功!');
                },
                onFail: () => {
                  console.error('关闭失败');
                },
              });
            }
          } else if (url) {
            this.$router.push({
              path: url,
            });
          } else {
            this.back();
          }
          return;
        }

        url =
          getUrlStroage(this.$route.query.return as string) ||
          (this.$route.query.return as string) ||
          (window.sessionStorage.getItem('fullPath') as string);
        console.log('url2=>', url);
        if (url) {
          this.$router.replace({
            path: url,
          });
          // this.$router.push(url)
        } else {
          this.goEmptyPage(res);
        }
      }, 1000);
    }
  }

  // retrieveCallBack() {
  //   const workflowInstanceId = this.$route.query.workflowInstanceId as string;
  //   const workitemId = this.$route.query.workitemId as string;
  //   const vm = this;
  //   this.timer = setInterval(() => {
  //       const params = {
  //           workflowInstanceId,
  //           activityCode: this.formObj.activityCode as string
  //       }
  //       workflowApi.isRetrieve(params).then(res => {
  //           if (res.errcode === 0) {
  //               if (!res.data) {
  //                   // 撤回成功获得新流程实例id 刷新表单
  //                   workflowApi.getWorkitemByInstanceid({ workflowInstanceId }).then(res => {
  //                       if (res.errcode === 0) {
  //                           vm.reload();
  //                           vm.workflowInstanceId = '';
  //                           vm.$nextTick(()=>{
  //                             vm.workflowInstanceId = workflowInstanceId;
  //                           });
  //                       }
  //                   });
  //                   clearInterval(vm.timer);
  //               }
  //           } else {
  //               this.$message.error(res.errmsg || '');
  //               clearInterval(vm.timer);
  //           }
  //       });
  //   },1000);
  // }

  goBizForm() {
    const url =
      getUrlStroage(this.$route.query.return as string) ||
      (this.$route.query.return as string);
    this.$router.replace({
      name: 'form-detail',
      query: {
        schemaCode: this.formObj.bizSchema.code,
        sheetCode: this.formObj.bizSheet.code,
        objectId: this.formObj.bizObject.id,
        return: url,
        t: new Date().getSeconds().toString() || '',
      },
    });
    this.clean();
    // this.reload();
  }

  goWfForm(workitemId: string, workflowInstanceId: string) {
    const url =
      getUrlStroage(this.$route.query.return as string) ||
      (this.$route.query.return as string);
    this.$router.replace({
      name: 'form-detail',
      query: {
        workitemId,
        workflowInstanceId,
        return: url,
        t: new Date().getSeconds().toString() || '',
      } as any,
    });
  }

  goEmptyPage(backData?: any) {
    if ((window as any).externalLinkToken && backData) {
      const { formCode, objectId, schemaCode, workflowInstanceId } =
        backData.data;
      let param: any = {
        formCode,
        objectId,
        schemaCode,
      };
      if ((window as any).isStartWorkflow) {
        param = { objectId, workflowInstanceId };
      }
      externalLinkApi.getShortCode(param).then((res: any) => {
        if (res.errcode === 0) {
          this.$router.replace({
            name: 'shared-success',
            params: { shortCode: res.data.pairCode },
          });
        }
      });
    } else {
      this.$router.replace({
        name: 'form-empty',
        query: {
          return: this.$route.query.return,
        },
      });
    }
  }

  goUnpublished() {
    this.$router
      .push({
        name: 'formUnpublished',
      })
      .catch((err: any) => {
        console.log(err);
      });
  }

  goPermission() {
    // this.$router.replace({
    //   name: "permission"
    // });
    const theUrl = `${env.portalHost}/mobile/#/permission`;
    window.location.href = theUrl;
  }

  flowTrack() {
    this.workflowTrackVisible = true;
  }

  /**
   * 获取评论数
   * */
  async getCommListNum() {
    const { id, schemaCode } = this.formObj.bizObject as any;
    if (!this.formObj) {
      return;
    }
    const params: FormCommentIns.formCommentParams.CommentList = {
      bizObjectId: id,
      schemaCode,
    };

    const res: any = await FormCommentIns.FormCommentApi.getCommentListNum(
      params,
    );
    if (res.errcode === 0) {
      const { data } = res;
      if (!this.isSsubmited || !this.isLoadComment) {
        return;
      }
      const item: any = this.actions.find(
        (ac: any) => ac.code === runtime.FormAction.Comment,
      );
      if (item) {
        // item.text = `${(this as any).$t('languages.common.comment', {
        //   data: data <= 99 ? data : '99+',
        // })}`;
        item.text = data <= 99 ? data : '99+';
      } else {
        this.actions.push({
          code: runtime.FormAction.Comment,
          // text: `${(this as any).$t('languages.common.comment', {
          //   data: data <= 99 ? data : '99+',
          // })}`,
          text: data <= 99 ? data : '99+',
          disabled: false,
          visible: true,
        });
      }
    } else {
      console.error(res.errmsg);
    }
  }

  onCloseModal(modal: string) {
    // if (modal === 'FormComment') {
    //   const title = this.formObj.instanceName || this.formObj.bizSheet.name;
    //   (window as any).pageTitle = title;
    //   platform.service.setTitle(title);
    //   this.getCommListNum();
    // }
  }

  showCustomListModal: boolean = false;

  async customButtonFun(customButtonType: any) {
    const beforeReuslt = await super.beforeAction(customButtonType);
    if (beforeReuslt === false) {
      return;
    }

    const { schemaCode } = this.$route.params;
    const objectId = this.$route.query.objectId;
    const params: any = {
      bizObjectId: objectId,
      schemaCode,
    };
    let sheetCodes: string = '';
    //自定义按钮
    if (customButtonType) {
      const customButtonData = this.customBtn.filter((x) => {
        return x.code === customButtonType.code;
      });
      if (customButtonData[0].operateType === 'WITH_VIEW') {
        switch (customButtonData[0].bindAction) {
          case 'LIST':
            const actionConfigs = JSON.parse(customButtonData[0].actionConfig);
            this.viewCodeCustom = actionConfigs.viewXListData[0].code;
            this.customButtomModalCode = actionConfigs.schemaCodeVal.key;
            this.searchFormula = actionConfigs.searchFormula || [];
            const opens = await this.customButtomCheck(
              'LIST',
              actionConfigs.schemaCodeVal.key,
            );
            // if (opens) {
            //   this.$router.push({
            //     path:
            //       '/apps/apps-form-list/' + actionConfigs.schemaCodeVal.value,
            //   });
            // }
            if (!opens) {
              return;
            }
            this.showCustomListModal = true;
            Back.subscribeBack({
              callback: (event: Event) => {
                if (event) {
                  event.preventDefault();
                }
                this.showCustomListModal = false;
                const title =
                  this.formObj.instanceName || this.formObj.bizSheet.name;
                platform.service.setTitle(title);
                return;
              },
            });
            Back.useScribeBack();
            return;
          case 'FORM':
          case 'ADD_DATA':
          case 'FLOW':
            const queryCondition: any = []; //当为查看列表时存储自定义按钮配置的筛选条件
            const addData: any = []; //当为新增数据时存储自定义按钮配置数据
            const actionConfig: any = JSON.parse(
              customButtonData[0].actionConfig,
            );
            if (this.formObj.bizObject) {
              const formJsonData = this.formObj.bizObject.data;
              for (const con of actionConfig.configureList) {
                let qcCon: any;
                if (customButtonData[0].bindAction === 'FORM') {
                  qcCon = {
                    propertyCode: '',
                    propertyType: 0,
                    propertyValue: '',
                    queryFilterType: 'Eq',
                  };
                } else if (
                  customButtonData[0].bindAction === 'ADD_DATA' ||
                  customButtonData[0].bindAction === 'FLOW'
                ) {
                  qcCon = {
                    targetDataItemCode: null,
                    targetDataItemValue: null,
                  };
                } else {
                  //Else Empty block statement
                }

                if (con.currentDataItem) {
                  //配置的是变量
                  for (const valKay in formJsonData) {
                    if (valKay === con.currentDataItem[0].code) {
                      if (customButtonData[0].bindAction === 'FORM') {
                        qcCon.propertyCode = con.targetDataItem[0].code;
                        qcCon.propertyType =
                          con.currentDataItem[0].propertyType;
                        qcCon.queryFilterType = con.OptionType;
                        if (Array.isArray(formJsonData[valKay])) {
                          for (const fon of formJsonData[valKay]) {
                            fon.unitType = fon.type;
                          }
                        }
                        qcCon.propertyValue = formatVal(
                          con.currentDataItem[0].propertyType,
                          formJsonData[valKay],
                          con.targetDataItem[0].code,
                          con.OptionType,
                        );
                        queryCondition.push(qcCon);
                      } else if (
                        customButtonData[0].bindAction === 'ADD_DATA' ||
                        customButtonData[0].bindAction === 'FLOW'
                      ) {
                        qcCon.targetDataItemCode = con.targetDataItem[0].code;
                        if (
                          [DataItemType.Date].includes(
                            con.currentDataItem[0].propertyType,
                          )
                        ) {
                          qcCon.targetDataItemValue = formatVal(
                            con.currentDataItem[0].propertyType,
                            formJsonData[valKay],
                            con.targetDataItem[0].code,
                            con.OptionType,
                          );
                        } else {
                          if (
                            con.targetDataItem[0].propertyType ===
                              DataItemType.RelevanceForm &&
                            valKay === 'id'
                          ) {
                            qcCon.targetDataItemValue = {
                              [valKay]: formJsonData[valKay],
                            };
                          } else {
                            qcCon.targetDataItemValue = formJsonData[valKay];
                          }
                        }
                        addData.push(qcCon);
                      } else {
                        //Else Empty block statement
                      }
                    } else {
                      //为子表时
                    }
                  }
                } else {
                  //配置的是常量
                  if (customButtonData[0].bindAction === 'FORM') {
                    qcCon.propertyCode = con.targetDataItem[0].code;
                    qcCon.propertyValue = con.currentDataInput;
                    //针对单选复选下拉单选下拉多选进行值转换
                    if (
                      [12, 13, 14, 15].includes(
                        con.targetDataItem[0].propertyType,
                      )
                    ) {
                      if (
                        typeof con.currentDataInput === 'object' &&
                        Array.isArray(con.currentDataInput)
                      ) {
                        qcCon.propertyValue = con.currentDataInput
                          .map((el) => el.label)
                          .join(';');
                      } else if (typeof con.currentDataInput === 'object') {
                        qcCon.propertyValue = con.currentDataInput.label;
                      }
                    }

                    const trimOpen = con.currentDataInput.trim();
                    if (trimOpen === '') {
                      qcCon.queryFilterType = 'IsNull';
                    }
                    queryCondition.push(qcCon);
                  } else if (
                    customButtonData[0].bindAction === 'ADD_DATA' ||
                    customButtonData[0].bindAction === 'FLOW'
                  ) {
                    if (con.targetDataItem) {
                      qcCon.targetDataItemCode = con.targetDataItem[0].code;
                      if (con.dynamicValue) {
                        const dynamicCon: any = {
                          propertyType:
                            con.targetDataItem.length > 0
                              ? con.targetDataItem[0].propertyType
                              : 0,
                          propertyCode: con.targetDataItemId,
                          operatorType: con.OptionType,
                          dynamicValue: con.dynamicValue,
                        };
                        qcCon.targetDataItemValue =
                          this.getDynamicValue(dynamicCon);
                      } else {
                        qcCon.targetDataItemValue = con.currentDataInput;

                        //针对单选复选下拉单选下拉多选进行值转换
                        if (
                          [12, 13, 14, 15].includes(
                            con.targetDataItem[0].propertyType,
                          )
                        ) {
                          if (
                            typeof con.currentDataInput === 'object' &&
                            Array.isArray(con.currentDataInput)
                          ) {
                            qcCon.targetDataItemValue = con.currentDataInput
                              .map((el) => el.label)
                              .join(';');
                          } else if (typeof con.currentDataInput === 'object') {
                            qcCon.targetDataItemValue =
                              con.currentDataInput.label;
                          }
                        }
                      }
                    }
                    addData.push(qcCon);
                  } else {
                  }
                }
              }
            }
            if (customButtonData[0].bindAction === 'FORM') {
              const formParams: any = {
                filters: [],
                mobile: false,
                page: 0,
                queryCode: '',
                queryVersion: 1,
                schemaCode: actionConfig.schemaCodeVal.key,
                size: 20,
                queryCondition: [],
              };
              const queryConditions: any = [];
              sheetCodes = actionConfig.formListData[0].code;
              queryConditions.push(queryCondition);
              formParams.queryCondition.push(queryConditions);
              const formRes = await listApi.getQueryList(formParams);
              if (formRes.data.content && formRes.data.content.length > 0) {
                const cusResData = formRes.data.content[0];
                params.bizObjectId = cusResData.id;
                params.schemaCode = cusResData.schemaCode;
              } else {
                this.$message.info('没有符合条件的数据', 4);
                return;
              }
            } else if (
              customButtonData[0].bindAction === 'ADD_DATA' ||
              customButtonData[0].bindAction === 'FLOW'
            ) {
              const actionConfigs = JSON.parse(
                customButtonData[0].actionConfig,
              );
              const addParams: any = {
                code: actionConfigs.schemaCodeVal.key,
                schemaCode: actionConfigs.schemaCodeVal.key,
                source: 1,
              };
              window.sessionStorage.setItem(
                'addDataCustom',
                JSON.stringify(addData),
              );
              const headerParams = {
                schemaCode: actionConfigs.schemaCodeVal.key,
                clientType: listParams.QueryClientType.PC,
              };
              const headerRes = await listApi.getQueryHeaders(headerParams);
              if (headerRes.errcode === 0 && Array.isArray(headerRes.data)) {
                addParams.code = headerRes.data[0]
                  ? headerRes.data[0].code
                  : actionConfigs.schemaCodeVal.key;
              }
              const addRes = await listApi.getListConfigData(addParams);
              if (addRes.data && addRes.data.queryActions) {
                const addQA = addRes.data.queryActions.filter((x) => {
                  return x.actionCode === 'add';
                });
                if (addQA.length > 0) {
                  customButtonData[0].bindAction === 'FLOW'
                    ? (addQA[0].associationType = 1)
                    : (addQA[0].associationType = 0);
                  customButtonData[0].bindAction === 'FLOW'
                    ? (addQA[0].associationCode =
                        actionConfigs.WorkflowListData[0].workflowCode)
                    : (addQA[0].associationCode =
                        actionConfigs.formListData[0].code);
                  if (customButtonData[0].bindAction === 'ADD_DATA') {
                    addQA[0].queryCode = actionConfigs.formListData[0].code;
                  }
                } else {
                  const addQAData: any = {};
                  if (customButtonData[0].bindAction === 'FLOW') {
                    addQAData.associationCode =
                      actionConfigs.WorkflowListData[0].workflowCode;
                    addQAData.associationType = 1;
                    addQAData.schemaCode = actionConfigs.schemaCodeVal.key;
                  } else if (customButtonData[0].bindAction === 'ADD_DATA') {
                    addQAData.associationCode =
                      actionConfigs.formListData[0].code;
                    addQAData.associationType = 0;
                    addQAData.schemaCode = actionConfigs.schemaCodeVal.key;
                    addQAData.queryCode = actionConfigs.formListData[0].code;
                  } else {
                  }
                  addQA.push(addQAData);
                }

                if (customButtonData[0].bindAction === 'FLOW') {
                  const flowParams = {
                    startWorkflowCode:
                      actionConfigs.WorkflowListData[0].workflowCode,
                  };
                  const flowRes = await formApi.load(flowParams);
                  if (flowRes.errcode !== 0) {
                    this.$message.error('执行失败，找不到模型/表单/视图');
                    return;
                  }
                } else if (customButtonData[0].bindAction === 'ADD_DATA') {
                  const opens = await this.customButtomCheck(
                    'ADD_DATA',
                    actionConfigs.schemaCodeVal.key,
                  );
                  if (!opens) {
                    return;
                  }
                } else {
                  //Else Empty block statement
                }

                this.handleAdd(addQA[0], true);
                return;
              }
            } else {
              //Else Empty block statement
            }
            break;
          default:
            break;
        }
      } else if (customButtonData[0].operateType === 'WITH_OUT_VIEW') {
        if (customButtonData[0].bindAction === 'BUSINESS_RULE') {
          this.customButtonRule(customButtonData[0], [objectId]);
        } else if (customButtonData[0].bindAction === 'SCRIPT') {
          const scriptData: any = JSON.parse(
            customButtonData[0].actionConfig,
          ).scriptData;
          try {
            let scriptDataFucs: any = new Function(
              'vm',
              'scriptData',
              scriptData,
            );
            scriptDataFucs.call(this, this.proxy, this.custargus);
          } catch (err) {
            console.log(err, '自定义按钮JS脚本编写有误，请检查');
          }
        } else {
          //Else Empty block statement
        }
        return;
      } else {
        //Else Empty block statement
      }

      const res = await listApi.getFormUrl(params);
      // 如果报错, 会返回一个对象
      if (typeof res === 'object' && res.errcode !== 0) {
        return this.$message.error(res.errmsg as string, 3);
      }
      // 否则返回一个字符串
      else if (typeof res === 'string') {
        let res1: any = res;
        if (res1.indexOf('sheetCode') !== -1 && sheetCodes) {
          const urlParts = (res as string).split('sheetCode=');
          res1 =
            urlParts[0] +
            'sheetCode=' +
            sheetCodes +
            '&' +
            urlParts[1].split('&').slice(1).join('&');
        }
        const questionPosition = location.href.indexOf('?');
        const search =
          location.href.substring(questionPosition) + '&iframeAction=detail';
        const url = this.isDingTalk
          ? `${res1}&return=${location.pathname}`
          : `${res1}&return=${location.pathname + encodeURIComponent(search)}`;
        this.$router.push({
          path: url,
        });
      } else {
        //Else Empty block statement
      }
    }
  }

  onCustomListModalClose() {
    this.showCustomListModal = false;
    const title = this.formObj.instanceName || this.formObj.bizSheet.name;
    platform.service.setTitle(title);
  }

  toFormDetail() {
    this.showCustomListModal = false;
    const openFormDetail = JSON.parse(
      sessionStorage.getItem('openFormDetail') || '{}',
    );
    openFormDetail[this.formObj.bizObject.id] = {
      viewCodeCustom: this.viewCodeCustom,
      customButtomModalCode: this.customButtomModalCode,
      searchFormula: this.searchFormula,
    };
    sessionStorage.setItem('openFormDetail', JSON.stringify(openFormDetail));
  }

  /**
   * 获取特殊动态值
   * @param el
   * @returns
   */
  getDynamicValue(el) {
    const { valueType, value } = el.dynamicValue;
    const userInfo: any = JSON.parse(
      window.sessionStorage.getItem('user') || '{}',
    );
    switch (valueType) {
      case ValueTypesWithoutInput.CurrentUser:
        const user = [
          {
            name: userInfo.name,
            id: userInfo.id,
            unitType: 3,
          },
        ];
        return formatVal(
          el.propertyType,
          user,
          el.propertyCode,
          el.operatorType,
        );
      case ValueTypesWithoutInput.CurrentDepartment:
        const department = [
          {
            name: userInfo.currentDeptName || userInfo.departmentName,
            id: userInfo.currentDeptId || userInfo.departmentId,
            unitType: 1,
          },
        ];
        return formatVal(
          el.propertyType,
          department,
          el.propertyCode,
          el.operatorType,
        );
      case ValueTypeWithInput.Today:
        const todayOffsetValue = value;
        const today = Helper.setDateByDateType(
          9,
          'YYYY-MM-DD HH:mm:ss',
          JSON.stringify({
            offsetValue: Number(todayOffsetValue),
            offsetUnit: 'day',
          }),
        );
        return formatVal(
          el.propertyType,
          today[0],
          el.propertyCode,
          el.operatorType,
        );
      case ValueTypesWithoutInput.Yesterday:
        const yesterday = Helper.setDateByDateType(12, 'YYYY-MM-DD HH:mm:ss');
        return formatVal(
          el.propertyType,
          yesterday[0],
          el.propertyCode,
          el.operatorType,
        );
      case ValueTypesWithoutInput.Tomorrow:
        const tomorrow = Helper.setDateByDateType(13, 'YYYY-MM-DD HH:mm:ss');
        return formatVal(
          el.propertyType,
          tomorrow[0],
          el.propertyCode,
          el.operatorType,
        );
      case ValueTypeWithInput.DynamicRange:
        const [dateType, offsetValue, offsetUnit] = value.split('-');
        const date = Helper.setDateByDateType(
          DateType[dateType],
          'YYYY-MM-DD HH:mm:ss',
          JSON.stringify({ offsetValue: Number(offsetValue), offsetUnit }),
        );
        return date.join(';');
      default:
        break;
    }
  }

  hiddenCommentBtn: boolean = false;

  actionInterval: any = null;

  formBodyScoll() {
    if (!this.hiddenCommentBtn) {
      this.hiddenCommentBtn = true;
    }
    if (this.actionInterval) {
      clearInterval(this.actionInterval);
    }
    this.actionInterval = setInterval(() => {
      this.hiddenCommentBtn = false;
      clearInterval(this.actionInterval);
    }, 800);
    // setTimeout(() => {
    //   this.hiddenCommentBtn = false;
    // },1500);
  }

  openCommentBox() {
    this.showCommentBox = true;
    Back.subscribeBack({
      callback: (event: Event) => {
        if (event) {
          event.preventDefault();
        }
        this.showCommentBox = false;
        const title = this.formObj.instanceName || this.formObj.bizSheet.name;
        platform.service.setTitle(title);
        this.getCommListNum();
        return;
      },
    });
    Back.useScribeBack();
  }

  closeCommentBox() {
    this.showCommentBox = false;
    const title = this.formObj.instanceName || this.formObj.bizSheet.name;
    platform.service.setTitle(title);
    this.getCommListNum();
  }

  onCloseCurrentDeptSetterModal() {
    let url: string =
      getUrlStroage(this.$route.query.return as string) ||
      (this.$route.query.return as string);
    if (
      this.$route.name === 'form-detail' &&
      location.pathname !== '/mobile/el.html'
    ) {
      if ((window as any).dd?.closePage) {
        if (url) {
          this.$router
            .push({
              path: url,
            })
            .catch((err: any) => {
              console.log(err);
            });
        } else {
          (window as any).dd?.closePage();
        }
      } else if (dd.biz && (dd.android || dd.ios)) {
        if (url) {
          this.$router
            .push({
              path: url,
            })
            .catch((err: any) => {
              console.log(err);
            });
        } else {
          dd.biz.navigation.goBack({
            onSuccess: () => {
              console.log('关闭成功!');
            },
            onFail: () => {
              console.error('关闭失败');
            },
          });
        }
      } else {
        this.back();
      }
      super.onCloseCurrentDeptSetterModal();
      return;
    }

    url =
      getUrlStroage(this.$route.query.return as string) ||
      (this.$route.query.return as string) ||
      (window.sessionStorage.getItem('fullPath') as string);

    if (url) {
      this.$router.replace({
        path: url,
      });
      // this.$router.push(url)
    } else {
      this.back();
    }
    super.onCloseCurrentDeptSetterModal();
  }

  onOkCurrentDeptSetterModal() {
    super.onOkCurrentDeptSetterModal();
  }

  initCustomListModelTimer: any = null;

  initCustomListModal(objectId?: string) {
    if ((this.formObj && this.formObj.bizObject) || objectId) {
      this.initCustomListModelTimer = null;
      const openFormDetail = JSON.parse(
        sessionStorage.getItem('openFormDetail') || '{}',
      );
      // openFormDetail[this.formObj.bizObject.id] = {
      //   viewCodeCustom: this.viewCodeCustom,
      //   customButtomModalCode: this.customButtomModalCode,
      //   searchFormula: this.searchFormula,
      // };
      if (openFormDetail[objectId || this.formObj.bizObject.id]) {
        const { viewCodeCustom, customButtomModalCode, searchFormula } =
          openFormDetail[objectId || this.formObj.bizObject.id];
        this.viewCodeCustom = viewCodeCustom;
        this.customButtomModalCode = customButtomModalCode;
        this.searchFormula = searchFormula;
        delete openFormDetail[this.formObj.bizObject.id];
        sessionStorage.setItem(
          'openFormDetail',
          JSON.stringify(openFormDetail),
        );
        this.showCustomListModal = true;
        Back.subscribeBack({
          callback: (event: Event) => {
            if (event) {
              event.preventDefault();
            }
            this.showCustomListModal = false;
            const title =
              this.formObj.instanceName || this.formObj.bizSheet.name;
            platform.service.setTitle(title);
            return;
          },
        });
        Back.useScribeBack();
      }
    } else {
      if (this.initCustomListModelTimer) {
        this.initCustomListModelTimer = null;
      }
      this.initCustomListModelTimer = setTimeout(this.initCustomListModal, 100);
    }
  }

  @Watch('$route')
  onRouteChange(to, from) {
    this.tab = 0;
    this.nodes = [];
    this.workflowBaseInfo = {};

    const { objectId } = to.query;
    if (objectId) {
      this.initCustomListModal(objectId);
    }
  }
}
</script>

<style lang="less" scoped>
@import '~@/styles/mixins.less';
@import '~@/styles/1px.less';

.shadow {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.45);
  z-index: 1001;
}
.add-type {
  position: fixed;
  z-index: 1002;
  width: 72%;
  overflow: hidden;
  padding: 16px;
  border-radius: 8px;
  background-color: #fff;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

.urgency-edit {
  background: #fff;
  box-shadow: inset 0px -0.5px 0px 0px rgba(209, 211, 228, 0.65);
}

.urgency-readonly {
  /deep/ .h3think-field {
    .h3think-label {
      font-size: 13px;
      font-weight: 400 !important;
      color: rgba(17, 18, 24, 0.5);
    }
  }
}

.add-type-item {
  display: flex;
  align-items: center;
  padding: 16px;
  position: relative;
  &:nth-child(1)::after {
    content: '';
    position: absolute;
    width: 200%;
    height: 1px;
    background-color: #999;
    left: 0;
    bottom: 0;
    transform: scale(0.5);
    transform-origin: left;
  }
  .add-type-icon {
    width: 43px;
    height: 43px;
    border-radius: 43px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(39, 113, 255, 0.1);
    i {
      color: #2970ff;
      font-size: 17px;
    }
  }
}
.add-type-text {
  display: flex;
  text-align: left;
  flex-direction: column;
  justify-content: center;
  margin-left: 19px;
  div {
    font-size: 17px;
    color: #333;
  }
  span {
    color: #999;
    font-size: 11px;
    margin-top: 8px;
  }
}

.form-detail {
  // display: flex;
  // flex-direction: column;
  height: 100%;
  position: relative;
  overflow-x: hidden;

  /deep/.h3-org-select {
    position: fixed;
  }

  // /deep/ .h3-panel > .h3-panel-header {
  //   .px2rem(font-size, @font-size-xl);
  //   // .px2rem(height, 90px);
  //   .px2rem(padding-left, 30px);
  //   .px2rem(padding-right, 30px);
  //   .px2rem(padding-top, 20px);
  //   .px2rem(padding-bottom, 20px);
  //   .hairline('bottom', #eee);
  //   display: block;
  //   // align-items: center;
  //   background-color: #f7f8fc;

  //   & > span {
  //     font-size: 18px;
  //     font-weight: 500;
  //     color: rgba(0, 0, 0, 0.85);
  //   }
  // }

  // 2023Q2移动端改造——分组标题样式
  /deep/.h3-panel.mobile-panel > .h3-panel-header {
    .px2rem(min-height, 120px);
    .px2remImp(padding, 32px);
    .px2rem(font-size, 36px);
    .px2rem(line-height, 56px);
    font-weight: 600;
    color: #111218;
    background: #ffffff;
    box-shadow: inset 0px -1px 0px 0px rgba(209, 211, 228, 0.65); // box-shadow: inset 0px -1px 0px 0px rgba(209, 211, 228, 0.65);
    border-bottom: unset;
    > span.span-title {
      // vertical-align: text-bottom;
      .px2remImp(font-size, 36px);
      .px2rem(margin-right, 12px);
      .px2rem(line-height, 56px);
    }
    > .h-icon-all-bevel-bottom-stroke {
      .px2rem(height, 56px);
      .px2rem(line-height, 56px);
      margin: unset;
      .px2rem(font-size, 28px);
      text-align: center;
      vertical-align: bottom;
    }
    &.center {
      justify-content: center;
    }
    &.right {
      justify-content: flex-end;
    }
  }

  // /deep/.desc {
  //   min-height: 2.8em;
  //   margin: 0.5em;
  //   .px2rem(margin-left, 30px);
  //   .px2rem(margin-right, 30px);
  // }
  // 2023Q2移动端改造——描述说明样式
  /deep/.desc {
    > div {
      .px2rem(font-size, 26px);
      font-weight: 400;
      color: rgba(17, 18, 24, 0.5);
      .px2rem(line-height, 40px);
    }
    > span {
      .px2rem(padding-top, 4px);
      .px2rem(padding-right, 20px);
      .px2rem(padding-bottom, 20px);
      .px2rem(padding-left, 20px);
      .px2rem(right, -20px);
      .px2rem(bottom, -20px);
      .px2rem(font-size, 26px);
      background-clip: content-box;
    }
    &.collapsed {
      .px2rem(max-height, 200px);
      overflow: hidden;
      padding: unset;
    }
  }
  /deep/.description {
    .px2rem(padding-top, 24px);
    .px2rem(padding-right, 32px);
    .px2rem(padding-bottom, 24px);
    .px2rem(padding-left, 32px);
    box-shadow: inset 0px -0.5px 0px 0px rgba(209, 211, 228, 0.65); // box-shadow: inset 0px -0.5px 0px 0px rgba(209,211,228,0.65);
    h1 {
      font-size: 2em;
    }

    h2 {
      font-size: 1.5em;
    }

    h3 {
      font-size: 1.17em;
    }

    h4 {
      font-size: 1em;
    }

    h5 {
      font-size: 0.83em;
    }

    h6 {
      font-size: 0.67em;
    }
  }

  /deep/.ant-tooltip {
    font-size: 14px;
    line-height: 1.5;
  }

  .comment-btn {
    position: fixed;
    bottom: 124px;
    right: 16px;
    height: 42px;
    background: #ffffff;
    box-shadow: 0px 4px 18px 0px rgba(17, 18, 24, 0.12);
    border-radius: 21px;
    padding: 10px 18px;
    display: flex;
    align-items: center;
    transition: all 0.25s ease-in;
    .comment-icon {
      display: inline-block;
      height: 20px;
      font-size: 20px;
      font-weight: 400;
      color: rgba(17, 18, 24, 0.5);
      line-height: 20px;
    }
    .comment-count {
      display: inline-block;
      margin-left: 8px;
      width: 9px;
      height: 22px;
      font-size: 15px;
      font-weight: 400;
      color: rgba(17, 18, 24, 0.5);
      line-height: 22px;
      text-align: center;
    }
    &.moreCount .comment-count {
      width: 28px;
    }
    &.hidden {
      right: -27px;
      opacity: 0.8;
      .comment-icon,
      .comment-count {
        color: rgba(17, 18, 24, 0.25);
      }
      &.moreCount {
        right: -46px;
      }
    }
  }

  &::-webkit-scrollbar {
    width: 0;
    height: 0;
    display: none;
  }
}

.form-body {
  overflow-x: hidden;
  overflow-y: auto;
  height: calc(100% - 36px);
  border-top: 1px solid transparent;
  background: #f1f2f3;
  transition: all 0.4s ease-in;
  &.hasnodes {
    background: #f5f6f9;
    height: calc(100% - 88px);
    border-radius: 20px 20px 0px 0px;
    box-shadow: 0px 2px 12px 0px rgba(222, 223, 229, 0.4);
  }
  .form {
    background-color: #fff;
  }
  .workflow-form {
  }

  &::-webkit-scrollbar {
    width: 0;
  }
}

// /deep/ .h3-swiper {
//   overflow: hidden !important;
// }
// /deep/.h3-swiper-item > div {
//   overflow-y: auto;
//   height: calc(100vh - 92.5px) !important;
// }

.form-foot {
  // flex-shrink: 0;
  // position: fixed;
  // z-index: 10;
  // bottom: 0;
  // width: 100%;
  // height: 24px;
  // box-sizing: border-box;
}

/deep/.toptip.error {
  color: @error-color;
  position: fixed;
  z-index: 11;
  background-color: @error-bg;
  bottom: 44px;
}
/deep/.h3-field-tip {
  @bgcolor: #323334;
  padding: 9px 16px !important;
  font-size: 15px;
  width: auto;
  color: #fff;
  background: @bgcolor;
  opacity: 0.8;
  border-radius: 4px;
  left: 17px;
  * {
    border-bottom-color: @bgcolor;
    border-top-color: @bgcolor;
  }
  .h3-field-tip-wrapper {
    overflow: auto;
    &::-webkit-scrollbar-thumb {
      background-color: @bgcolor;
    }
    &::-webkit-scrollbar-track {
      background-color: @bgcolor;
    }
  }
}
/deep/.h3-field-label-tip {
  .icon-base-question-circle-o {
    font-family: 'aufontAll' !important;
    margin-left: 7px;
    &:before {
      content: '\E9A9';
      color: rgba(0, 0, 0, 0.25);
    }
  }
}
</style>

<style lang="less">
.form-confirm-modal {
  &.cancel,
  &.finishInstance {
    .h3think-modal__content .h3think-modal__body {
      padding: 0 54px 18px 54px;
    }
  }
  &.retrieve {
    .h3think-modal__content .h3think-modal__body {
      padding: 0 60px 18px 60px;
    }
  }
  .h3think-modal__content {
    width: 280px;
    padding-top: 22px;
    .h3think-modal__body {
      font-size: 15px;
      color: #111218;
      line-height: 22px;
      padding: 0 24px 18px 24px;
    }
    .h3think-modal__footer {
      border-top: 0.5px solid rgba(209, 211, 228, 0.65);
      .h3think-button {
        font-size: 16px;
        height: 50px;
        color: #2970ff;
        &:first-child {
          color: #111218;
          &::after {
            width: 0.5px;
          }
        }
      }
    }
  }
}
</style>

<style lang="less">
.radio-wrap.current-dept-setter-modal {
  .h3think-popup-modal__header .options-group {
    height: 68px;
    .options-sub-group {
      width: 50px;
      min-width: 50px;
      max-width: 50px;
    }
    .panel-title {
      text-align: center;
      > span {
        height: 26px;
        font-size: 16px;
        font-weight: 600;
        color: #111218;
        line-height: 26px;
      }
      .panel-title-tips {
        height: 18px;
        font-size: 12px;
        font-weight: 400;
        color: rgba(17, 18, 24, 0.5);
        line-height: 18px;
      }
    }
  }
}
</style>
